<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>查看用户</title>
</head>
<body>
<jsp:include page="/incloud/header.jsp"/>

<div class="d-flex align-items-stretch">
    <!-- Sidebar Navigation-->
    <jsp:include page="/incloud/sidebar.jsp"/>
    <!-- Sidebar Navigation end-->
    <div class="page-content">
        <div class="page-header">
            <div class="container-fluid">
                <h2 class="h5 no-margin-bottom">用户列表</h2>
            </div>
        </div>
        <section class="no-padding-bottom">
            <div class="title">
                <form class="form-inline" id="search">
                    <div class="form-group">
                        <label for="inlineFormInput" class="sr-only">Name</label>
                        <input id="inlineFormInput" type="text" placeholder="按名字查找" class="mr-sm-3 form-control">
                    </div>
                    <div class="form-group">
                        <input type="submit" value="查询" class="btn btn-primary">
                    </div>
                </form>

            </div>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>年龄</th>
                        <th>简介</th>
                        <th>操作</th>
                        <th>加关注</th>
                    </tr>
                    </thead>
                    <tbody id="userTable">
                    </tbody>
                </table>

                <nav class="text-center" aria-label="Page navigation">
                    <ul class="pagination">
                    </ul>
                </nav>
            </div>
        </section>

        <jsp:include page="/incloud/footer.jsp"/>
    </div>
</div>

<!-- JavaScript files-->


<script type="text/javascript">

    $(function () {
        // 初始化用户列表
        getUserList("", 1);

        // 用户列表，查看详情
        $(document).on("click", ".userDetail", function () {
            var userId = $(this).data("id"); // 获取 data-id 属性的值
            console.log("Clicked user ID:", userId);
            window.location.href = '/html/user_detail.jsp?userId=' + userId;
        });

        // 检查框点击事件
        $(document).on("click", ".checkbox-template", function () {
            var userId = $(this).val(); // 获取复选框的 value 值，即 record.id
            var isChecked = $(this).prop("checked"); // 获取复选框的选中状态

            if (isChecked) {
                $.ajax({
                    url: "/user/focus",
                    type: "post",
                    data: {
                        userId: userId
                    },
                    dataType: "json",
                    success: function (response) {
                        if (response.code === 200) {
                            layer.msg("关注成功，用户 ID: " + userId);
                        } else {
                            layer.msg("关注失败，用户 ID: " + userId);
                        }
                    },
                })
            } else {
                $.ajax({
                    url: "/user/unfocus",
                    type: "post",
                    data: {
                        userId: userId
                    },
                    dataType: "json",
                    success: function (response) {
                        if (response.code === 200) {
                            layer.msg("取关成功，用户 ID: " + userId);
                        } else {
                            layer.msg("取关失败，用户 ID: " + userId);
                        }
                   },
                })
            }
        });

        // 搜索表单提交事件
        $("#search").submit(function (event) {
            event.preventDefault(); // 阻止表单默认提交行为
            var name = $("#inlineFormInput").val();
            getUserList(name, 1); // 提交查询时调用 getUserList 函数
        });

        // 获取用户列表的函数
        function getUserList(name, page) {
            $.ajax({
                url: "/user/getAllUsers",
                type: "get",
                data: {
                    name: name,
                    page: page
                },
                dataType: "json",
                success: function (response) {
                    if (response && response.data) {
                        var data = response.data;
                        console.log(data)
                        var html = data.records.map(function (record) {
                            return "<tr>" +
                                "<th scope='row'>" + record.id + "</th>" +
                                "<td>" + record.username + "</td>" +
                                "<td>" + (record.sex === '0' ? '女' : '男') + "</td>" +
                                "<td>" + record.age + "</td>" +
                                "<td>" + record.info + "</td>" +
                                "<td><input type='button' value='详细信息' class='btn-xs btn-primary userDetail' data-id='" + record.id + "'></td>" +
                                "<td><input type='checkbox' value='" + record.id + "' class='checkbox-template'></td>" +
                                "</tr>";
                        }).join("");

                        // 更新表格内容
                        $("#userTable").html(html);

                        // 更新分页
                        updatePagination(data.page, data.totalPage);
                    } else {
                        layer.msg("数据加载失败，请稍后重试");
                    }
                },
                error: function () {
                    layer.msg("网络错误，请稍后重试");
                }
            });
        }

        // 更新分页的函数
        function updatePagination(currentPage, totalPages) {
            console.log(currentPage, totalPages);

            var paginationHtml = "";
            paginationHtml += "<li class='" + (currentPage === 1 ? "disabled" : "") + "'>";
            paginationHtml += "<a href='#' aria-label='Previous' data-page='" + (currentPage - 1) + "'>";
            paginationHtml += "<span aria-hidden='true'>&laquo;</span>";
            paginationHtml += "</a>";
            paginationHtml += "</li>";

            for (var i = 1; i <= totalPages; i++) {
                paginationHtml += "<li class='" + (i === currentPage ? "active" : "") + "'>";
                paginationHtml += "<a href='#' data-page='" + i + "'>" + i + "</a>";
                paginationHtml += "</li>";
            }

            paginationHtml += "<li class='" + (currentPage === totalPages ? "disabled" : "") + "'>";
            paginationHtml += "<a href='#' aria-label='Next' data-page='" + (currentPage + 1) + "'>";
            paginationHtml += "<span aria-hidden='true'>&raquo;</span>";
            paginationHtml += "</a>";
            paginationHtml += "</li>";


            $(".pagination").html(paginationHtml);

            // 使用事件委托绑定分页按钮的点击事件
            $(".pagination").off("click", "a").on("click", "a", function (event) {
                event.preventDefault();
                var page = $(this).data("page");
                var currentPage = parseInt($(".pagination .active a").data("page"), 10); // 获取当前页码

                // 如果点击的是当前页按钮，直接返回
                if (page === currentPage) {
                    return;
                }

                // 确保 page 是有效的数字
                if (page && !isNaN(page)) {
                    getUserList("", page);
                }
            });
        }
    });

</script>
<style>
    .disabled {
        pointer-events: none;
    }
</style>
</body>
</html>